package com.jzlw.huozhuduan.network.httpservice;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.blankj.utilcode.util.ActivityUtils;
import com.jzlw.huozhuduan.BuildConfig;
import com.jzlw.huozhuduan.Utlis.JSONUtils;
import com.jzlw.huozhuduan.appction.MyAPP;
import com.jzlw.huozhuduan.ui.activity.LoginActivity;


import org.json.JSONObject;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import io.reactivex.observers.DisposableObserver;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

/**
 * ClassName OnSuccessAndFaultSub
 * Description 成功失败订阅
 * Author sr
 * Date 2019/3/26 14:33
 */
public class OnSuccessAndFaultSub extends DisposableObserver<ResponseBody> {

    private OnSuccessAndFaultListener mOnSuccessAndFaultListener;
    private OnPageInfoListener mOnPageInfoListener;
    private Context context;

    /**
     * @param mOnSuccessAndFaultListener 成功回调监听
     */
    public OnSuccessAndFaultSub(OnSuccessAndFaultListener mOnSuccessAndFaultListener) {
        this.mOnSuccessAndFaultListener = mOnSuccessAndFaultListener;
    }

    /**
     * 包含总的数据条数的回调
     */
    public OnSuccessAndFaultSub(OnSuccessAndFaultListener mOnSuccessAndFaultListener, OnPageInfoListener mOnPageInfoListener) {
        this.mOnSuccessAndFaultListener = mOnSuccessAndFaultListener;
        this.mOnPageInfoListener = mOnPageInfoListener;
    }


    /**
     * @param mOnSuccessAndFaultListener 成功回调监听
     * @param context                    上下文
     */

    public OnSuccessAndFaultSub(OnSuccessAndFaultListener mOnSuccessAndFaultListener, Context context) {
        this.mOnSuccessAndFaultListener = mOnSuccessAndFaultListener;
        this.context = context;
    }


    /**
     * @param mOnSuccessAndFaultListener 成功回调监听
     * @param context                    上下文
     * @param showProgress               是否需要显示默认Loading
     */
    public OnSuccessAndFaultSub(OnSuccessAndFaultListener mOnSuccessAndFaultListener, Context context, boolean showProgress) {
        this.mOnSuccessAndFaultListener = mOnSuccessAndFaultListener;
        this.context = context;
    }

    /**
     * 当result等于1回调给调用者，否则自动显示错误信息，若错误信息为401跳转登录页面。
     * ResponseBody  body = response.body();//获取响应体
     * InputStream inputStream = body.byteStream();//获取输入流
     * byte[] bytes = body.bytes();//获取字节数组
     * String str = body.string();//获取字符串数据
     */
    @Override
    public void onNext(ResponseBody body) {
        onSuccess(body);
    }

    private void onSuccess(ResponseBody body) {
        try {
            String result = body.string();
            JSONObject jsonObject = new JSONObject(result);
            int resultCode = jsonObject.getInt("code");
            if (resultCode == 200) {
                //不管后台返回数据data里面是list或者map，都进行获取数据
                Object data = jsonObject.get("data");

                String data1 = String.valueOf(data);
                if (BuildConfig.DEBUG) {
                    Log.e("返回数据", "返回数据==" + data1);
                }
                Object message = jsonObject.get("msg");
                // Object sign = jsonObject.get("sign");
                //                Object timeStamp = jsonObject.get("timeStamp");
                //                String timeStamp1 = String.valueOf(timeStamp);
                //                //判断sign是否相同
                //                String sig1 = String.valueOf(sign);
                //                if (!ToolUtil.GetSign(data1, "key", timeStamp1).equals(sig1)) {
                //                    mOnSuccessAndFaultListener.onSuccess(data1, "请求不合法");
                //                }
                String message1 = String.valueOf(message);
                mOnSuccessAndFaultListener.onSuccess(data1, message1);
                //添加页码信息。
                if(mOnPageInfoListener!=null){
                    String mpageInfo = jsonObject.getString("page");
                    PageInfoEntity mPageInfoEntity= JSONUtils.fromJson(mpageInfo,PageInfoEntity.class);
                    mOnPageInfoListener.onPageInfo(mPageInfoEntity);
                }

            } else {
                int code = jsonObject.getInt("code");
                Object data = jsonObject.get("data");
                String data1 = String.valueOf(data);
                if (BuildConfig.DEBUG) {
                    Log.e("返回数据", "返回数据==" + data1);
                }
                String errorMsg = jsonObject.getString("msg");
                Log.e("OnSuccessAndFaultSub", "errorMsg: " + errorMsg);
                if (code == 401) {
                    mOnSuccessAndFaultListener.onFault(code, errorMsg);
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("flag", 1);
                    Intent intent = new Intent(MyAPP.getContext(), LoginActivity.class);
                    intent.putExtra("flag", 1);
                    ActivityUtils.startActivity(intent);
                } else {
                    mOnSuccessAndFaultListener.onFault(code, errorMsg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 完成
     */
    @Override
    public void onComplete() {

    }

    /**
     * 对错误进行统一处理
     * 隐藏ProgressDialog
     */
    @Override
    public void onError(Throwable e) {
        try {
            if (e instanceof SocketTimeoutException) {//请求超时  自定义code301
                mOnSuccessAndFaultListener.onFault(301, "请求超时");
            } else if (e instanceof ConnectException) {//网络连接超时  自定义code302
                mOnSuccessAndFaultListener.onFault(302, "网络连接超时");
            } else if (e instanceof SSLHandshakeException) {//安全证书异常  自定义code303
                mOnSuccessAndFaultListener.onFault(303, "安全证书异常");
            } else if (e instanceof HttpException) {//请求的地址不存在
                int code = ((HttpException) e).code();
                if (code == 401) {  //UNAUTHORIZED
                    mOnSuccessAndFaultListener.onFault(401, "您的账号已在其他设备登录");
                } else if (code == 403) {  //FORBIDDEN
                    mOnSuccessAndFaultListener.onFault(403, "禁止访问");
                } else if (code == 404) {  //NOT_FOUND
                    mOnSuccessAndFaultListener.onFault(404, "请求的地址不存在");
                } else if (code == 408) {  //REQUEST_TIMEOUT
                    mOnSuccessAndFaultListener.onFault(408, "链接超时");
                } else if (code == 500) {  //INTERNAL_SERVER_ERROR
                    mOnSuccessAndFaultListener.onFault(500, "服务器出错了");
                } else if (code == 502) {  //BAD_GATEWAY
                    mOnSuccessAndFaultListener.onFault(502, "服务器无响应");
                } else if (code == 503) {  //SERVICE_UNAVAILABLE
                    mOnSuccessAndFaultListener.onFault(503, "服务器维护或者过载");
                } else if (code == 504) {  //GATEWAY_TIMEOUT
                    mOnSuccessAndFaultListener.onFault(504, "网络异常，请检查您的网络状态");
                } else {
                    mOnSuccessAndFaultListener.onFault(304, "请求失败"); //其他HttpException 自定义code304
                }
            } else if (e instanceof UnknownHostException) {//域名解析失败  自定义code305
                mOnSuccessAndFaultListener.onFault(305, "域名解析失败");
            } else {
                if (e.getMessage() == null)    //e.getMessage() == null  INTERNAL_SERVER_ERROR 服务器出错了
                    mOnSuccessAndFaultListener.onFault(500, "请求出错，稍后再试");
                else if (e.getMessage().equals("NoNet"))  //DISNETWORK  自定义code606 无网络
                    mOnSuccessAndFaultListener.onFault(606, "网络似乎出问题啦！");
                else if (e.getMessage().contains("ms") && e.getMessage().contains("connect"))  //链接超时 连接超时504
                    mOnSuccessAndFaultListener.onFault(504, "链接超时");
                else
                    mOnSuccessAndFaultListener.onFault(306, "error = " + e.getMessage());  //其他异常  自定义code306
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            if (BuildConfig.DEBUG)
                Log.e("OnSuccessAndFaultSub", "error = " + e.getMessage());
            //            mOnSuccessAndFaultListener.onFault("error:" + e.getMessage());
        }
    }

}
